<template>
  <div class="flex-d-col h-100%">
    <breadcrumb />
    <div class="app-main-container h-100% flex">
      <div class="left flex-d-col">
        <div class="title">题库目录</div>
        <organizeQuestionBanks
          :rightShow="true"
          :addBtnShow="true"
          @ac-question-data="
            (val, data) => {
              getQuestion(val, data);
            }
          "
        ></organizeQuestionBanks>
      </div>
      <div class="right flex-d-col flex-1 ml-20px">
        <div class="title">题目列表</div>
        <div class="flex-d-col h-100% of-hidden">
          <div class="search">
            <el-form :inline="true" :model="formSearch" size="small">
              <el-form-item label="来源">
                <!-- <el-tree-select
                  v-model="formSearch.regulationId"
                  :data="data"
                  check-strictly
                  :render-after-expand="false"
                  style="width: 240px"
                /> -->
                <el-select
                  v-model="formSearch.regulationId"
                  placeholder="请输入选择"
                  clearable
                  filterable
                  class="min-w-150px"
                  @change="getQuestionList()"
                >
                  <el-option
                    v-for="item in optionsList.regulation"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-date-picker
                  v-model="formSearch.publishTime"
                  type="date"
                  class="w-120px!"
                  placeholder="选择发布日期"
                  @change="getQuestionList()"
                />
              </el-form-item>
              <el-form-item>
                <el-input
                  v-model="formSearch.regulationNum"
                  class="w-120px"
                  clearable
                  @change="getQuestionList()"
                >
                  <template #prepend>第</template>
                  <template #append>条</template>
                </el-input>
              </el-form-item>
              <el-form-item>
                <el-select
                  v-model="formSearch.category"
                  placeholder="选择类型"
                  clearable
                  class="min-w-100px"
                  @change="getQuestionList()"
                >
                  <el-option
                    v-for="item in optionsList.dictionary"
                    :label="item.text"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-select
                  v-model="formSearch.type"
                  placeholder="选择题型"
                  clearable
                  class="min-w-100px"
                  @change="getQuestionList()"
                >
                  <el-option
                    v-for="(item, key) in QuestionTypeEnum"
                    :label="item"
                    :value="parseInt(key)"
                  />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-input
                  v-model="formSearch.filter"
                  placeholder="输入搜索关键词"
                  :prefix-icon="Search"
                  clearable
                  @change="getQuestionList()"
                ></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" text @click="advancedSearch = !advancedSearch">
                  高级搜索
                  <el-icon class="el-icon--right">
                    <ArrowUp v-if="advancedSearch" />
                    <ArrowDown v-else />
                  </el-icon>
                </el-button>
              </el-form-item>
              <!-- <el-form-item>
              <el-button type="primary" @click="onSubmit">Query</el-button>
            </el-form-item> -->
            </el-form>
            <el-form
              v-show="advancedSearch"
              :inline="true"
              :model="formSearch"
              size="small"
            >
              <el-form-item>
                <el-select
                  v-model="formSearch.jobPostId"
                  placeholder="选择适用工种"
                  clearable
                  class="min-w-100px"
                  @change="
                    (val) => {
                      if (!val) {
                        delete formSearch.difficulty;
                        delete formSearch.period;
                      }
                      getQuestionList();
                    }
                  "
                >
                  <el-option
                    v-for="item in optionsList.jobType"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <template v-if="formSearch.jobPostId">
                <el-form-item>
                  <el-select
                    v-model="formSearch.difficulty"
                    placeholder="选择难度"
                    clearable
                    class="min-w-80px"
                    @change="getQuestionList()"
                  >
                    <el-option
                      v-for="(item, key) in jobCList.difficulty"
                      :label="item"
                      :value="parseInt(key)"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-select
                    v-model="formSearch.period"
                    placeholder="选择学习周期"
                    clearable
                    class="min-w-60px"
                    @change="getQuestionList()"
                  >
                    <el-option
                      v-for="(item, key) in jobCList.period"
                      :label="item"
                      :value="parseInt(key)"
                    />
                  </el-select>
                </el-form-item>
              </template>
            </el-form>
          </div>
          <div class="search-con flex-d-col of-auto">
            <div class="flex-x-between">
              <el-checkbox
                v-model="checkAll"
                :indeterminate="isIndeterminate"
                @change="handleCheckAllChange"
                >全选</el-checkbox
              >
              <div class="btn" v-if="questionBankData.id">
                <el-button type="primary" size="small" @click="addEditSubject('add')"
                  >添加题目</el-button
                >
                <el-popconfirm title="确认要批量删除吗？" @confirm="delBatch">
                  <template #reference>
                    <el-button
                      size="small"
                      type="danger"
                      :disabled="!isIndeterminate && !checkAll"
                      plain
                      >批量删除</el-button
                    >
                  </template>
                </el-popconfirm>
              </div>
            </div>
            <div class="con of-auto">
              <template v-for="(item, index) in questionList">
                <div class="list flex flex-items-baseline">
                  <div class="w-30px">
                    <el-checkbox
                      v-model="item.check"
                      @change="handleCkeckboxListChange"
                    ></el-checkbox>
                  </div>
                  <div class="w-66px">
                    <span class="type">{{ QuestionTypeEnum[item.type] }}</span>
                  </div>
                  <div class="flex-1">
                    <div class="flex-x-between flex-items-baseline">
                      <div class="title flex-1">
                        {{ index + 1 }}.&nbsp;{{ item.content }}
                      </div>
                      <el-space :size="4" class="ml-10">
                        <el-button
                          type="primary"
                          size="small"
                          link
                          @click="addEditSubject('detail', item.id)"
                          >查看</el-button
                        >
                        <el-button
                          type="primary"
                          size="small"
                          link
                          @click="addEditSubject('edit', item.id)"
                          >编辑</el-button
                        >
                        <el-popconfirm title="确认要删除？" @confirm="del(item)">
                          <template #reference>
                            <el-button type="danger" size="small" link>删除</el-button>
                          </template>
                        </el-popconfirm>
                      </el-space>
                    </div>
                    <div class="answer mb-8px pl-10px">
                      <!-- 单选，多选，判断 -->
                      <div v-if="item.type == 1 || item.type == 2 || item.type == 3">
                        <el-checkbox
                          v-for="v in item.questionOptions"
                          v-model="v.isCorrect"
                          :label="`${v.options}.${v.content}`"
                          disabled
                        />
                      </div>
                      <!-- 填空、问答 -->
                      <template v-else-if="item.type == 4 || item.type == 5">
                        <div class="flex" v-for="(v, i) in item.questionOptions">
                          <span>{{ i + 1 }}、</span>
                          <span>{{ v.content }}</span>
                        </div>
                      </template>
                    </div>
                    <div class="source">
                      来源：{{ item.regulationName }}<br />
                      适用工种：{{ item.jobPostNames }}
                    </div>
                  </div>
                </div>
                <el-divider />
              </template>
              <template v-if="questionList.length == 0">
                <el-empty description="暂无数据" />
              </template>
            </div>
            <div class="w-100%">
              <el-pagination
                class="flex-x-center mt-10px"
                small
                background
                layout="prev, pager, next"
                v-model:current-page="page.index"
                :page-size="page.size"
                :total="page.total"
                hide-on-single-page
                @current-change="pageChange"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- <router-view /> -->
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Theory",
  inheritAttrs: false,
});
import {
  ApiGetQuestion,
  ApiDelQuestionId,
  ApiGetJob,
  ApiDelQuestionBatch,
} from "@/api/resource-management/theory";
import { Search } from "@element-plus/icons-vue";
import organizeQuestionBanks from "@/components/organizeQuestionBanks/index.vue";
import { QuestionTypeEnum } from "@/enums/QuestionTypeEnum";
import { ApiGetRegulation } from "@/api/resource-management/regulations";
import { ApiGetDictionaryCode } from "@/api/data-dictionary/index";

const route = useRoute();
const router = useRouter();

const { params, query } = route;
const { path } = params;

const formSearch = ref({});
const advancedSearch = ref(false); // 高级搜索

watch(advancedSearch, (newVal, oldVal) => {
  delete formSearch.value.difficulty;
  delete formSearch.value.period;
  if (oldVal && formSearch.value.jobPostId) {
    delete formSearch.value.jobPostId;
    getQuestionList();
  }
  delete formSearch.value.jobPostId;
});

// 添加，修改，查看 试题
const addEditSubject = (type, rowId = null) => {
  // router.push(`${route.path}/add`);
  router.push(
    `${route.path}/${type}?qId=${questionBankData.id}&data=${JSON.stringify(
      questionBankData
    )}${rowId != null ? "&id=" + rowId : ""}`
  );
  // router.push(
  //   `${route.path}/subject/${type}?qId=${questionBankData.id}${
  //     rowId != null ? "&id=" + rowId : ""
  //   }`
  // );
};
// 删除试题
const del = (data) => {
  ApiDelQuestionId(data).then((res) => {
    if (res.code == 200) {
      ElMessage({
        message: "删除成功！",
        type: "success",
      });
      getQuestionList(page.index);
    }
  });
};
// 删除试题
const delBatch = () => {
  ApiDelQuestionBatch(questionList.value.filter((e) => e.check).map((e) => e.id)).then(
    (res) => {
      if (res.code == 200) {
        ElMessage({
          message: "批量删除成功！",
          type: "success",
        });
        getQuestionList(page.index);
      }
    }
  );
};

const questionList = ref([]);
const questionBankData = reactive({
  id: "",
  name: "",
  data: {},
});
const getQuestion = (val, data) => {
  if (val == "" || val == null || questionBankData.id == val.id) return;
  // debugger;
  questionBankData.id = val.id;
  questionBankData.name = val.questionBank;
  questionBankData.data = data;
  getQuestionList();
};
const getQuestionList = (pageIndex: number = 1) => {
  page.index = pageIndex;
  checkAll.value = false;
  isIndeterminate.value = false;
  if (!questionBankData.id) {
    return;
  }
  let params = {
    source: "",
    number: 0,
    questionKind: null,
    quetionType: null,
    keyWord: "",
    ...questionBankData.data,
    questionBank: questionBankData.name,
    ...formSearch.value,
  };
  ApiGetQuestion(params).then((res) => {
    if (res.code == 200) {
      questionList.value = res.data?.map((e) => {
        return {
          ...e,
          type: e.quetionType + 1,
          check: false,
        };
      });
      page.total = res.data.totalCount;
    }
  });
};
onActivated(() => {
  if (questionBankData.id) {
    getQuestionList(page.index);
  }
});

const ckeckboxList = ref([]);
const checkAll = ref(false);
const isIndeterminate = ref(false);
const handleCheckAllChange = (val: boolean) => {
  questionList.value = questionList.value.map((e) => {
    return {
      ...e,
      check: val,
    };
  });
  // ckeckboxList.value = val ? questionList.value.map((e) => e.id) : [];
  isIndeterminate.value = false;
};
const handleCkeckboxListChange = () => {
  const checkedCount = questionList.value.filter((e) => e.check).length;
  checkAll.value = checkedCount === questionList.value.length;
  isIndeterminate.value = checkedCount > 0 && checkedCount < questionList.value.length;
};

const optionsList = reactive({
  jobType: [],
  regulation: [],
  dictionary: [],
});
// 获取适用工种下拉
ApiGetJob({ MaxResultCount: 999 }).then((res) => {
  if (res.code == 200) {
    optionsList.jobType = res.data.items;
  }
});
// 获取规章
ApiGetRegulation({ MaxResultCount: 999, isActive: true }).then((res) => {
  if (res.code == 200) {
    optionsList.regulation = res.data.items;
  }
});
// 获取题型
ApiGetDictionaryCode({ code: "QuestionCategory" }).then((res) => {
  if (res.code == 200) {
    optionsList.dictionary = res.data;
  }
});
// 工种下的难度和学习周期
const jobCList = {
  difficulty: {
    1: "简单",
    2: "一般",
    3: "困难",
    4: "地狱",
  },
  period: {
    1: "周",
    2: "月",
    3: "季",
    4: "年",
  },
};

// watch(formSearch.value, (newVal, oldVal) => {
//   if (newVal.content == oldVal.content && newVal.content != "") {
//     console.log(newVal);
//   }
// });

// 分页
const page = reactive({
  index: 1,
  size: 10,
  total: 0,
});
const pageChange = (val: number) => {
  page.index = val;
  getQuestionList(val);
};

// ApiGetQuestion({
//   ...formSearch.value,
//   skipCount: (page.index - 1) * page.size,
//   maxResultCount: page.size,
// }).then((res) => {
//   if (res.code == 200) {
//     questionList.value = res.data.items.map((e) => {
//       return {
//         ...e,
//         check: false,
//       };
//     });
//     page.total = res.data.totalCount;
//   }
// });
</script>

<style scope lang="scss">
.app-main-container {
  .title {
    font-family: Source Han Sans CN, Source Han Sans CN;
    font-weight: bold;
    font-size: 16px;
    color: rgba(0, 0, 0, 0.9);
    line-height: 21px;
    text-align: left;
    font-style: normal;
    text-transform: none;
    margin-bottom: 20px;
  }
  .left {
    height: 100%;
    // & > .flex {
    //   background: linear-gradient(180deg, #ffffff 0%, rgba(255, 255, 255, 0.8) 100%);
    //   border-radius: 20px 20px 20px 20px;
    //   border: 1px solid rgba(7, 113, 255, 0.4);
    //   overflow: hidden;
    // }
    // .tree1 {
    //   background: linear-gradient(180deg, #60a5ff 0%, #2a7aeb 100%);
    //   border-radius: 20px 20px 20px 20px;
    //   padding: 16px 12px;
    //   .el-tree {
    //     margin-top: 20px;
    //     background: transparent;
    //     color: #fff;
    //     &-node {
    //       &__content {
    //         border-radius: 6px;
    //         &:hover {
    //           background-color: #67a8ff;
    //         }
    //       }
    //     }
    //     &--highlight-current {
    //       .el-tree-node.is-current > .el-tree-node__content {
    //         background-color: var(--el-color-primary-light-3);
    //       }
    //     }
    //     &__empty-text {
    //       color: #fff;
    //     }
    //   }
    // }
    // .tree2 {
    //   // padding: 16px 20px;
    //   ul {
    //     li {
    //       padding: 10px 20px;
    //       &:hover,
    //       &.ac {
    //         background: linear-gradient(
    //           90deg,
    //           var(--el-color-primary) 0%,
    //           var(--el-color-primary-light-3) 100%
    //         );
    //         color: #fff;
    //       }
    //     }
    //   }
    // }
  }
  .right {
    & > .flex-d-col {
      background: linear-gradient(180deg, #ffffff 0%, rgba(255, 255, 255, 0.8) 100%);
      border-radius: 20px 20px 20px 20px;
      border: 1px solid rgba(4, 42, 94, 0.1);
      padding: 20px;
    }
    .el-input {
      &-group__append,
      &-group__prepend {
        padding: 0 10px;
      }
    }
    .con {
      border: 1px solid rgba(0, 57, 137, 0.1);
      border-radius: 20px 20px 0px 0px;
      padding: 10px 20px 20px;
      .el-checkbox-group {
        font-size: 14px;
        line-height: inherit;
      }
      .list {
        .title {
          margin-bottom: 10px;
        }
        .type {
          background-color: #1759b5;
          font-size: 12px;
          padding: 4px 8px;
          border-radius: 6px;
          color: #fff;
        }
        .answer {
          font-size: 12px;
          color: rgba(0, 0, 0, 0.6);
          pointer-events: none;
        }
        .source {
          border: 1px solid rgba(0, 0, 0, 0.1);
          padding: 8px;
          border-radius: 10px;
          font-size: 12px;
          color: rgba(0, 0, 0, 0.6);
        }
      }
    }
  }
}
</style>
